<template>
    <div>
          <el-form :inline="true" :model="form" class="demo-form-inline">
    <el-form-item label="发票号：" style="width: 280px;">
      <el-input v-model="form.invoiceNumber" placeholder="请输入发票号" clearable />
    </el-form-item>
    <el-form-item label="发票类型：">
      <el-select
        v-model="form.invoiceType"
        placeholder="请选择发票类型"
        clearable
        style="width: 180px;"
      >
        <el-option label="普通发票" :value="1" />
        <el-option label="增值税专用发票" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="开票日期：">
      <el-date-picker
        v-model="form.invoiceDate"
        type="date"
        placeholder="请选择日期"
        clearable
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getInvoiceList">查询</el-button>
    </el-form-item>
  </el-form>
        <el-button type="primary" size="default" @click="Add">新增</el-button>
        <el-button type="danger" @click="batchDelete()">批量删除</el-button>
        <el-button type="success" @click="exportExcel">导出Excel</el-button>
        <!-- 打印 -->
         <el-button type="warning" size="default" @click="printInvoice()">打印</el-button>
        <el-table :data="tableData" border style="width: 100%"  @selection-change="handleSelectionChange">
             <el-table-column type="selection"  width="55"  />
            <el-table-column prop="invoiceNumber" label="发票号" width="center" />
            <el-table-column prop="invoicingUnit" label="开票单位" width="center" />
            <el-table-column prop="invoiceType" label="发票类型" width="center" >
                <!-- 普通发票=1,增值税专用发票 -->
                 <template v-slot="scope">
                    <el-tag v-if="scope.row.invoiceType === 1">普通发票</el-tag>
                    <el-tag v-else type="success">增值税专用发票</el-tag>
                 </template>
            </el-table-column>
            <el-table-column prop="invoiceMoney" label="发票金额" width="center" />
            <el-table-column prop="invoiceRate" label="税率" width="center" />
            <!-- <el-table-column prop="invoiceTax" label="税额" width="center" >
                <template v-slot="scope">
                    {{ scope.row.invoiceMoney * scope.row.invoiceRate / 100 }}
                </template>
            </el-table-column> -->
            <el-table-column prop="invoiceDate" label="开票日期" width="center" >
                <template v-slot="scope">
                    {{ scope.row.invoiceDate.split('T')[0] }}
                </template>
            </el-table-column>
            <el-table-column prop="invoiceRemark" label="备注" width="center" />
             <el-table-column prop="createNames" label="制单人" width="center" />
            <el-table-column prop="createDates" label="创建时间" width="center">
                <template v-slot="scope">
                     <span v-if="scope.row.createDates!=null">
                         {{ (scope.row.createDates).substring(0,10) +' '+ (scope.row.createDates).substring(11,16) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right"  min-width="220" align="center">
                <template v-slot="scope">
                    <el-button type="primary" link @click="upd(scope.row.invoiceId)">编辑</el-button>
                    <el-button type="primary" link @click="Del(scope.row.invoiceId)">删除</el-button>
                    <el-button type="primary" link @click="check(scope.row.invoiceId)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div>
        <table>
            <tr>
                <td>
                    <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
                        :page-sizes="[3, 5, 8, 10]" :background="true" layout="total, slot" prev-text="上一页"
                        next-text="下一页" :total="form.listCount" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange">
                        每页显示{{ form.pageSize }}条，当前第{{ form.pageIndex }}/{{ form.pageCount }}页
                    </el-pagination>
                </td>
                <td><el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
                        :page-sizes="[3, 5, 8, 10]" :background="true" layout=" slot,prev, pager, next" prev-text="上一页"
                        next-text="下一页" :total="form.listCount" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" @hide-on-single-page="form.pageIndex = 1">
                        <el-button type="primary" :disabled="form.pageIndex == 1" size="small"
                            @click="handleCurrentChange(1)">首页</el-button>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize"
                        :page-sizes="[3, 5, 8, 10]" :background="true" layout="slot, sizes, jumper" prev-text="上一页"
                        next-text="下一页" :total="form.listCount" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" @hide-on-single-page="form.pageIndex = form.pageCount">
                        <el-button type="primary" :disabled="form.pageIndex == form.pageCount" size="small"
                            @click="handleCurrentChange(form.pageCount)">尾页</el-button>
                    </el-pagination>
                </td>
            </tr>
        </table>
    </div>

    <!-- <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[3, 5, 8, 10]"
        :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="form.listCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" /> -->
  <el-dialog v-model="dialogTableVisible" title="查看进项发票" width="1100">
             <el-table :data="invoiceData">
             <el-table-column prop="invoiceNumber" label="发票号" width="center" />
            <el-table-column prop="invoicingUnit" label="开票单位" width="center" />
            <el-table-column prop="invoiceType" label="发票类型" width="center" >
                <!-- 普通发票=1,增值税专用发票 -->
                 <template v-slot="scope">
                    <el-tag v-if="scope.row.invoiceType === 1">普通发票</el-tag>
                    <el-tag v-else type="success">增值税专用发票</el-tag>
                 </template>
            </el-table-column>
            <el-table-column prop="invoiceMoney" label="发票金额" width="center" />
            <el-table-column prop="invoiceRate" label="税率" width="center" />
            <!-- <el-table-column prop="invoiceTax" label="税额" width="center" >
                <template v-slot="scope">
                    {{ scope.row.invoiceMoney * scope.row.invoiceRate / 100 }}
                </template>
            </el-table-column> -->
            <el-table-column prop="invoiceDate" label="开票日期" width="center" >
                <template v-slot="scope">
                    {{ scope.row.invoiceDate.split('T')[0] }}
                </template>
            </el-table-column>
            <el-table-column prop="invoiceRemark" label="备注" width="center" />
            </el-table>
  </el-dialog>
        
        
</template>
<script setup lang="ts">
import { ref, reactive, inject, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import http from '@/Http';
import axios from 'axios';
const tableData = ref([])
const router = useRouter();
import * as XLSX from 'xlsx';
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { EditPen } from '@element-plus/icons-vue'

 components: {
    EditPen
  }

const form = reactive({
    pageIndex: 1,
    pageSize: 3,
    pageCount: 0,
    listCount: 0,
    invoiceNumber: '',
    invoiceType: '',
    invoiceDate:'',
})

const getInvoiceList = () => {
    axios.get("Settlementread/api/Invoicess/Get", {
        params: {
            pageIndex: form.pageIndex,
            pageSize: form.pageSize,
            invoiceNumber: form.invoiceNumber,
            invoiceType: form.invoiceType || 0,
            invoiceDate: form.invoiceDate,
        }
    })
        .then(res => {
            form.listCount = res.data.data.listCount
            form.pageCount = res.data.data.pageCount
            tableData.value = res.data.data.pageList;
        
    })
}
const dialogTableVisible=ref(false)
const invoiceData:any=ref([])
//查看
const check=(invoiceId:any)=>{
  dialogTableVisible.value=true
  axios.get('Settlementwrite/api/Invoices/GetById', {
      params: {
          invoiceId: invoiceId
    }
  }).then((ret) => {
    invoiceData.value=[ret.data.data]
    console.log(invoiceData.value);
    
  })
}


//导出
const exportExcel = () => {
    const tableDataWithHeaders = [
        ['发票号', '客户名称', '发票类型', '发票金额', '利率', '发票日期', '制单人', '备注'],
        ...tableData.value.map((item:any )=> [
            item.invoiceNumber,
            item.invoicingUnit,
            item.invoiceType == 1 ? '普通发票' : '增值税发票',
            item.invoiceMoney,
            item.invoiceRate,
            item.invoiceDate,
            item.createNames,
            item.invoiceRemark,
        ]),
    ];
    const worksheet = XLSX.utils.json_to_sheet(tableDataWithHeaders)
        // 创建一个工作簿，并将工作表添加到工作簿中
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 将工作簿转换为Excel文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

      // 创建一个Blob对象，并将Excel文件数据添加到Blob对象中
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocumentspreadsheetml.sheet' });

      // 创建一个下载链接，并将Blob对象设置为链接的href属性
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;

      // 设置下载文件的名称
      link.download = 'data.xlsx';

      // 模拟点击链接以触发文件下载
      link.click();

      // 释放URL对象
      URL.revokeObjectURL(url);
}     
//打印
const selectedData = ref(null); // 创建一个响应式变量，用于存储选中的数据
const selectedData1 = ref([]); // 创建一个响应式变量，用于存储选中的数据

//创建打印内容
const createPrintContent = (data: any) => {
    if (!data || data.length == 0) return ''; // 如果没有数据，则返回空字符串

    let printContent = '<div style="font-family:Arial;sans-serif;">'; // 创建一个div，用于存储打印内容
    printContent += '<h1>进项发票详情</h1>'; // 添加标题
    printContent += '<table border="1" style="width:100%;border-collapse:collapse;">'; // 创建一个表格，用于存储发票信息
    printContent += '<thead><tr><th>发票号</th><th>开票单位</th><th>发票类型</th><th>发票金额</th><th>利率</th><th>发票日期</th><th>制单人</th><th>备注</th></tr></thead>'; // 添加表头

    data.forEach((item:any) => { // 遍历数据，将数据添加到表格中
        printContent += '<tr>';
        printContent += `<td>${item.invoiceNumber}</td>`;
        printContent += `<td>${item.invoicingUnit}</td>`;
        printContent += `<td>${item.invoiceType == 1 ? '普通发票' : '增值税发票'}</td>`;
        printContent += `<td>${item.invoiceMoney}</td>`;
        printContent += `<td>${item.invoiceRate}</td>`;
        printContent += `<td>${item.invoiceDate.substring(0, 10)}</td>`;
        printContent += `<td>${item.createNames}</td>`;
        printContent += `<td>${item.invoiceRemark}</td>`;
        printContent += '</tr>';
    });

    printContent += '</table>';
    printContent += '</div>';
    return printContent;
}


const printInvoice = () => {
    
    // 判断如果没有勾选数据就提示请选择要打印的数据
    if (selectedData1.value.length == 0) {
        ElMessage({
            message: "请选择要打印的数据",
            type: "warning"
        });
        return;
    }

    // 调用window.print()方法来实现打印
    const printContent = createPrintContent(selectedData1.value);
    const printWindow = window.open('', '_blank');
    printWindow?.document.write(printContent);
    printWindow?.document.close();
    printWindow?.print();
    printWindow?.close();
}

//导入
// const importExcel = (event: any) => {
//      const file = event.target.files[0];
//     const reader = new FileReader();

//      reader.onload = (e: any) => {
//         const data = new Uint8Array(e.target.result);
//         const workbook = XLSX.read(data, { type: 'array' });
//         const worksheet = workbook.Sheets[workbook.SheetNames[0]];
//         const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

//          // 在这里处理导入的数据
//         tableData.value = jsonData;
//         console.log(jsonData);
//     };

//     reader.readAsArrayBuffer(file);
       
// }
//修改
const upd = (invoiceId: any) => {
    router.push("/InvoiceUpdate?invoiceId=" + invoiceId);
}

//删除
const Del = (invoiceId: number) => {
    ElMessageBox.confirm(
        '您确定要删除此用户吗?', // 提示信息
        '确认删除', // 标题
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 用户点击“确定”后执行删除操作
        axios.post("Settlementwrite/api/Invoices/Delete?invoiceId=" + invoiceId).then(res => {
            if (res.data.data > 0) {
                ElMessage({
                    message: "删除成功",
                    type: "success"
                });
                getInvoiceList(); // 刷新用户列表
            } else {
                ElMessage({
                    message: "删除失败",
                    type: "warning"
                });
            }
        });
    }).catch(() => {
        // 用户点击“取消”后，可以选择不执行任何操作，或者显示提示
        ElMessage({
            message: "已取消删除",
            type: "info"
        });
    });
}

const nultipleSelection = ref([])
let invoiceId = ""
const handleSelectionChange = (val: any) => {
    let ids: any = []
    nultipleSelection.value = val;
    selectedData1.value = val;
     if (val.letter > 0) {
        selectedData.value = val;
    } else {
        selectedData.value = null;
    }
    val.forEach((item: any) => {
        ids.push(item.invoiceId)
    })
    invoiceId = ids.join(',')
}
//批量删除
const batchDelete = () => {
    if (invoiceId == "") {
        ElMessage({
            message: "请选择要删除的用户",
            type: "warning"
        });
        return;
    }
    ElMessageBox.confirm(
        '您确定要删除这些用户吗?', // 提示信息
        '确认删除', // 标题
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 用户点击“确定”后执行删除操作
        axios.post("Settlementwrite/api/Invoices/Delete?invoiceId=" + invoiceId)
            .then(res => { 
            if (res.data.data > 0) {
                ElMessage({
                    message: "删除成功",
                    type: "success"
                });
                getInvoiceList(); // 刷新用户列表
            } else {
                ElMessage({
                    message: "删除失败",
                    type: "warning"
                });
            }
        });
    }).catch(() => {
        // 用户点击“取消”后，可以选择不执行任何操作，或者显示提示
        ElMessage({
            message: "已取消删除",
            type: "info"
        });
    });
}

//跳转添加页面
const Add = () => {
    router.push("/InvoiceAdd");
}

const Role = () => {
    router.push("/roleView");
}

const formatTime = (time: any) => {
    return time.replace('T', ' ').slice(0, 16); // 只保留前10位
}


const handleSizeChange = (val: number) => {
    //console.log(`${val} items per page`)
    form.pageSize = val;
    getInvoiceList();
}
const handleCurrentChange = (val: number) => {
    form.pageIndex = val;
    getInvoiceList();
}

onMounted(() => {
    getInvoiceList();
})



</script>
<style scoped>
td {
  text-align: right;
  margin-right: 20px;
}
</style>

     <style scoped>
       .el-pagination {
            justify-content: flex-end;
        }
        
    </style>
<style scoped>
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>